/**
 * Created by DING on 2025/3/11.
 * */
#include "Task1.h"
#include <iostream>
#include <cstdlib>
#include <vector>
#include <fcntl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <sys/stat.h>
#include <cstring>
#include <mutex>
#include <thread>
#include <chrono>
std::mutex mtx;  // 声明互斥锁

BaseObject *createTask1() {
    return new Task1();
}

void destroyTask1(BaseObject *p) {
    SAFE_DELETE(p);
}

Task1::Task1(){
    const char* shm_name = "ZywyMem";
    // const size_t size = sizeof(std::complex<double>) * 6;//六个数字的内存dyh
    const size_t size = sizeof(std::complex<float>) * 250001; // 假设我们有 250000 个复数

    printf("###################   ID=%d   ####################", size);
    // 创建共享内存
    shm_fd = shm_open(shm_name, O_CREAT | O_RDWR, 0666);
    if (shm_fd == -1) {
        perror("shm_open");
        return ;
    }
    // 设置共享内存大小
    if (ftruncate(shm_fd, size) == -1) {
        perror("ftruncate");
        close(shm_fd);
        return ;
    }
    // 映射共享内存
    shm_ptr = mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0);
    if (shm_ptr == MAP_FAILED) {
        std::cerr << "mmap 失败!" << std::endl;
        close(shm_fd);
        return ;
    }
    shared_memory = static_cast<std::complex<float>*>(mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, shm_fd, 0));
    if (shared_memory == MAP_FAILED) {
        perror("mmap");
        close(shm_fd);
        return ;
    }
}

Task1::~Task1() {
}

/* 如果使用了DDS_Reader或者DDS_Writer，则对应的input或者output前64个字节为DataFormat head首部 */
void Task1::onCompute(buffer_table_t *input, buffer_table_t *output) {
//LOG_INFO("(%lld)onCompute:%s", this->outputSequence, this->instanceName.c_str());

  /** 获取端口数据指针示例
   * const char *src0 = input->list[0]->data;
   * char *dest0 = output->list[0]->data;
   * */
//    auto start = std::chrono::high_resolution_clock::now();
    float epsilon = 1e-6; // 定义一个很小的阈值
    std::complex<float>* dataPtr = reinterpret_cast<std::complex<float>*>(input->list[0]->data);
    // std::cout << "### " << dataPtr[4006] << " vs " << "; ????????????" << std::endl;
    mtx.lock(); // 获取共享内存锁
    // 将 input 中的复数数据赋值到 shared_memory
    shared_memory[0].real(-1.01);
    shared_memory[0].imag(-1.01);
    // std::cout << "### Task1::onCompute 1.5 " << shared_memory[0].real() << "+j" << shared_memory[0].imag() << "; ????????" << std::endl;
    // 将输入设置到共享内存中
    std::memcpy(shared_memory + 1, dataPtr, 250000 * sizeof(dataPtr[0]));
    // for (int i = 1; i < 250001; ++i) {
    //     shared_memory[i] = dataPtr[i-1];  // 将复数从 input 复制到 shared_memory
    // }
    // for (int i = 1; i < 250000; ++i) {
    //     shared_memory[i].real(i*0.1);
    //     shared_memory[i].imag(i*0.2);
    // }
    // 等待Python侧处理结束
    while (true) {
        if (std::abs(shared_memory[0].real() - 8.81)<epsilon || std::abs(shared_memory[0].imag() - 8.8)<epsilon) {
            break;
        }
        // std::cout << "### Task1::onCompute 3 " << shared_memory[0].real() << " + j" << shared_memory[0].imag() << "; ????????" << std::endl;
        // std::this_thread::sleep_for(std::chrono::milliseconds(1000));
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
    }
    mtx.unlock(); // 释放共享内存锁

//    auto end = std::chrono::high_resolution_clock::now();
//    // 计算时间间隔
//    std::chrono::duration<double> duration = end - start;


    // 输出结果（时间单位为秒）
//    std::cout << "Time taken: " << duration.count() << " seconds" << std::endl;
//    std::cout << "### Task1::onCompute 3" << dataPtr[4006] << std::endl;


    int num;
    memcpy(&num, (char*)shm_ptr + 8, sizeof(int));

    // **4. 输出读取到的值**
//    std::cout << "点的数量: " << num << std::endl;
    size_t copy_size = 4 + 32 * num;
    memcpy(output->list[0]->data, (char *)shm_ptr + 8, copy_size);
//    std::cout << "数据已成功拷贝到 output->list[0]->data，大小: " << copy_size << " 字节" << std::endl;
//    unsigned char* byte_ptr = (unsigned char*)output->list[0]->data;
//    for (size_t i = 0; i < copy_size ; i++) {
//        printf("%02X ", output->list[0]->data[i]);
//        if ((i + 1) % 16 == 0) std::cout << std::endl;
//    }
//    std::cout << std::endl;
    // 显示处理结果
//    for (int i = 0; i < 32; ++i) {
//        std::cout << "### " << shared_memory[i] << std::endl;
//    }
  /** 计算示例
   * if (input->list[0]->valid) {
   *     memcpy(dest0, src0, std::min(input->list[0]->len, output->list[0]->len));
   *   }
   * */
}
